﻿using System;
using System.IO;
using System.Diagnostics;

namespace SublimeTextBuildDotNetFile
{
    class Program
    {
        static void Main(string[] args)
        {
        	if(args.Length>0)
        	{
        		var file = args[args.Length-1];
        		var folder = Path.GetDirectoryName(file);

        		var csprojFile=FindCsprojFile(folder);

        		if(string.IsNullOrEmpty(csprojFile))
        		{

        		}
        		else
        		{
        			Run(csprojFile);
        		}
        	}
        	else
        	{
        		Console.WriteLine("You should input file");
        	}
        }

        static void Run(string csproj)
        {
        	csproj = $"\"{csproj}\"";
        	var str = $"run --project {csproj}";
        	Process.Start("dotnet",str);
        }

        static string FindCsprojFile(string folder)
        {
        	if(string.IsNullOrEmpty(folder))
        	{
        		return null;
        	}

            var fileList = Directory.GetFiles(folder,"*.csproj");

        	if(fileList.Length >= 1)
        	{
        		return fileList[0];
        	}
        	else if(fileList.Length ==0)
        	{
        		return FindCsprojFile(Directory.GetParent(folder).FullName);
        	}

        	return null;
        }
    }
}
